/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.support;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.aopalliance.intercept.MethodInvocation;

import org.springframework.aop.IntroductionInfo;
import org.springframework.util.ClassUtils;

/**
 * Support for implementations of {@link org.springframework.aop.IntroductionInfo}.
 *
 * <p>Allows subclasses to conveniently add all interfaces from a given object,
 * and to suppress interfaces that should not be added. Also allows for querying
 * all introduced interfaces.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 */
/*
1. 总结
	实现了 IntroductionInfo 接口，提供引入接口信息的管理功能
	提供了方便的方法来添加、移除和查询引入的接口
	支持缓存方法调用结果以提高性能
2. 内部成员解释
	publishedInterfaces：存储所有已发布的引入接口的集合
	rememberedMethods：缓存方法调用结果的映射表
	suppressInterface(Class<?> ifc)：抑制指定接口，使其不被发布到代理级别
	getInterfaces()：返回所有已发布的引入接口数组
	implementsInterface(Class<?> ifc)：检查指定接口是否为引入接口
	implementInterfacesOnObject(Object delegate)：将委托对象实现的所有接口发布到代理级别
	isMethodOnIntroducedInterface(MethodInvocation mi)：判断方法调用是否在引入接口上
	readObject(ObjectInputStream ois)：序列化支持方法

3 相关的接口和类
IntroductionInfo (接口)
├── IntroductionAdvisor (子接口)
│   ├── DefaultIntroductionAdvisor (实现类)
│   │   ├── TimestampIntroductionAdvisor (实现类)
│   │   └── LockMixinAdvisor (实现类)
│   └── DeclareParentsAdvisor (实现类)
└── IntroductionInfoSupport (实现类)
    ├── DelegatingIntroductionInterceptor (实现类)
    │   ├── LockMixin (实现类)
    │   └── TimestampIntroductionInterceptor (实现类)
    └── DelegatePerTargetObjectIntroductionInterceptor (实现类)

    关系说明
		IntroductionInfo：顶层接口，定义了获取引入接口的方法
		IntroductionAdvisor：IntroductionInfo 的子接口，扩展了引入顾问的功能
		IntroductionInfoSupport：抽象支持类，实现了 IntroductionInfo 接口
		DefaultIntroductionAdvisor：默认的引入顾问实现，可以包装任何实现了 IntroductionInfo 的对象
		DeclareParentsAdvisor：实现了声明式父类功能，允许在运行时为对象添加新的接口实现
		DelegatingIntroductionInterceptor：所有目标对象共享同一个委托实例，通过委托机制实现引入功能，将方法调用转发给目标对象
		DelegatePerTargetObjectIntroductionInterceptor：为每个目标对象提供独立的引入拦截器实例
		LockMixin 和 TimestampIntroductionInterceptor：具体的引入拦截器实现，分别用于锁定功能和时间戳功能

		DelegatePerTargetObjectIntroductionInterceptor DelegatingIntroductionInterceptor 区别
			1. 委托对象管理方式
				DelegatingIntroductionInterceptor:
				使用单一委托对象处理所有目标对象的引入接口实现
				所有目标对象共享同一个委托实例
				DelegatePerTargetObjectIntroductionInterceptor:
				为每个目标对象创建独立的委托实例
				实现了更细粒度的隔离，避免状态共享问题
			2. 适用场景
				DelegatingIntroductionInterceptor:
				适用于无状态的引入功能
				当引入接口的实现不需要维护目标对象特定的状态时使用
				DelegatePerTargetObjectIntroductionInterceptor:
				适用于需要维护目标对象特定状态的引入功能
				每个目标对象都需要独立的引入实现状态
			3. 性能与资源消耗
				DelegatingIntroductionInterceptor:
				资源消耗较少，只需要一个委托实例
				性能相对更好
				DelegatePerTargetObjectIntroductionInterceptor:
				每个目标对象都需要创建委托实例，资源消耗较大
				在大量目标对象场景下需要注意内存使用
4. 使用场景
	AOP 引入功能：向现有类动态添加新的接口实现
	混入（Mixin）模式：为多个类添加通用功能
	动态代理增强：在运行时扩展对象的功能
	声明式父类：通过配置而非代码修改来添加新功能
5 实际代码应用示例
// 创建引入拦截器
public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {

    private boolean locked;

    @Override
    public void lock() {
        this.locked = true;
    }

    @Override
    public void unlock() {
        this.locked = false;
    }

    @Override
    public boolean locked() {
        return this.locked;
    }

    // 重写 invoke 方法来控制访问
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
            throw new IllegalStateException("Locked object cannot be modified");
        }
        return super.invoke(invocation);
    }
}




 */
@SuppressWarnings("serial")
public class IntroductionInfoSupport implements IntroductionInfo, Serializable {

	protected final Set<Class<?>> publishedInterfaces = new LinkedHashSet<>();

	private transient Map<Method, Boolean> rememberedMethods = new ConcurrentHashMap<>(32);


	/**
	 * Suppress the specified interface, which may have been autodetected
	 * due to the delegate implementing it. Call this method to exclude
	 * internal interfaces from being visible at the proxy level.
	 * <p>Does nothing if the interface is not implemented by the delegate.
	 * @param ifc the interface to suppress
	 */
	public void suppressInterface(Class<?> ifc) {
		this.publishedInterfaces.remove(ifc);
	}

	@Override
	public Class<?>[] getInterfaces() {
		return ClassUtils.toClassArray(this.publishedInterfaces);
	}

	/**
	 * Check whether the specified interfaces is a published introduction interface.
	 * @param ifc the interface to check
	 * @return whether the interface is part of this introduction
	 */
	public boolean implementsInterface(Class<?> ifc) {
		for (Class<?> pubIfc : this.publishedInterfaces) {
			if (ifc.isInterface() && ifc.isAssignableFrom(pubIfc)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Publish all interfaces that the given delegate implements at the proxy level.
	 * @param delegate the delegate object
	 */
	protected void implementInterfacesOnObject(Object delegate) {
		this.publishedInterfaces.addAll(ClassUtils.getAllInterfacesAsSet(delegate));
	}

	/**
	 * Is this method on an introduced interface?
	 * @param mi the method invocation
	 * @return whether the invoked method is on an introduced interface
	 */
	protected final boolean isMethodOnIntroducedInterface(MethodInvocation mi) {
		Boolean rememberedResult = this.rememberedMethods.get(mi.getMethod());
		if (rememberedResult != null) {
			return rememberedResult;
		}
		else {
			// Work it out and cache it.
			boolean result = implementsInterface(mi.getMethod().getDeclaringClass());
			this.rememberedMethods.put(mi.getMethod(), result);
			return result;
		}
	}


	//---------------------------------------------------------------------
	// Serialization support
	//---------------------------------------------------------------------

	/**
	 * This method is implemented only to restore the logger.
	 * We don't make the logger static as that would mean that subclasses
	 * would use this class's log category.
	 */
	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
		// Rely on default serialization; just initialize state after deserialization.
		ois.defaultReadObject();
		// Initialize transient fields.
		this.rememberedMethods = new ConcurrentHashMap<>(32);
	}

}
